package com.xsq.rpc.common.config;

import org.springframework.boot.web.context.WebServerInitializedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * @ClassName ServerConfig
 * @Description TODO
 * @Author xsq
 * @Date 2020/6/8 16:41
 **/

@Component
public class ServerConfig implements ApplicationListener<WebServerInitializedEvent> {
    private int serverPort;

    /**
     * 获取启动项目的地址
     *
     * @return
     */
    public String getUrl() {
        return getIP() + ":" + this.serverPort;
    }

    /**
     * 获取启动项目的ip
     *
     * @return
     */
    public String getIP() {
        InetAddress address = null;
        try {
            address = InetAddress.getLocalHost();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        return address.getHostAddress();
    }

    /**
     * 获取启动项目的端口号
     *
     * @return
     */
    public int getPort() {
        return this.serverPort;
    }

    @Override
    public void onApplicationEvent(WebServerInitializedEvent event) {
        this.serverPort = event.getWebServer().getPort();
    }

}
